import { lazyReportBatch } from "../report";

export default function observeEntries() {
  if (document.readyState === "complete") {
    observerEvent();
  } else {
    const onLoad = () => {
      observerEvent();
      window.removeEventListener("load", onLoad, true);
    };
    window.addEventListener("load", onLoad, true);
  }
}

export function observerEvent() {
  let entryHandler = (list) => {
    const data = list.getEntries();
    for (let entry of data) {
      if (observer) {
        observer.disconnect();
      }
      const reportData = {
        name: entry.name, // 资源名称
        type: "performance", // 资源类型
        subType: entry.entryType, // 资源子类型
        sourceType: entry.initiatorType, // 资源来源类型
        duration: entry.duration, // 资源加载耗时
        tcp: entry.connectEnd - entry.connectStart, // tcp连接时间
        dns: entry.domainLookupEnd - entry.domainLookupStart, // DNS解析时间
        redirect: entry.redirectEnd - entry.redirectStart, // 重定向时间
        ttfb: entry.redirectStart, // 首字节时间
        protocol: entry.nextHopProtocol, // 协议类型
        responseBodySize: entry.encodedBodySize, // 响应体大小
        transferSize: entry.transferSize, // 传输大小
        responseHeaderSize: entry.transferSize - entry.encodedBodySize, // 响应头大小
        resourceSize: entry.decodedBodySize, // 资源解压大小
        starttime: performance.now(), // 资源开始加载时间
      };
      console.log(entry);
      // 发送数据
      lazyReportBatch(reportData)
    }
  };

  let observer = new PerformanceObserver(entryHandler);
  observer.observe({
    type: ["resource"],
    buffered: true,
  });
}
